import { InboxOutlined } from '@ant-design/icons';
import { Modal, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import axios from 'axios';
import React, { useState } from 'react';
import './index.less'
import {BASE_URL} from "../../../proxyConfig";
const MNTPrefix = BASE_URL;
const { Dragger } = Upload;
const App: React.FC = (props: any) => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [url, setURL] = useState('');

  const draggerProps: UploadProps = {
    name: 'file',
    // multiple: true,
    style: {
      width: 300,
    },
    onChange(info) {},
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },

    async customRequest(param) {
      const { onSuccess, onError, file, onProgress } = param;
      const config = {
        headers: { 'content-type': 'multipart/form-data' },
      };
      let formData = new FormData();
      formData.append('fileList', file);

      try {
        const response = await axios.post('/api/v1/photo/uploadList', formData, config);
        props.fileResponse.push(response.data.data[0]);
        props.setResponse(props.fileResponse);
        onSuccess(response);
        // setPreviewImage(MNTPrefix+response.data.data[0].src);
        // setPreviewOpen(true);
        // setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
      } catch (error) {
        onError({ error });
      }
    },
  };
  const onChange: UploadProps['onChange'] = async ({ file, fileList: newFileList }) => {
    await props.setFileList(newFileList);
    // props.form.setFieldValue('uploadImgs', props.fileList);
  };

  const onPreview = async (file: UploadFile) => {
    // if (!file.url && !file.preview) {
    //   file.preview = await getBase64(file.originFileObj as RcFile);
    // }
    if (file.response) {
      setPreviewImage(MNTPrefix + file.response.data.data[0].src);
    } else {
      setPreviewImage(file.url);
    }

    setPreviewOpen(true);
    setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
  };
  const onRemove = (file) => {
    let responseSrc = '';
    let currentFiles = [];
    if (file.response) {
      responseSrc = file.response.data.data[0].src;
      currentFiles = props.fileResponse;
    } else {
      responseSrc = file.src;
      currentFiles = props.fileList;
    }
    currentFiles.splice(
      currentFiles.findIndex((item) => item.src === responseSrc),
      1,
    );
    props.setResponse(currentFiles);
  };
  const handleCancel = () => setPreviewOpen(false); //根据官方属性定制化裁剪框大小固定的裁剪组件属性
  const propsCrop = {
    width: 500, //裁剪宽度
    height: 300, //裁剪高度
  };
  return (
    <>
      <ImgCrop
        rotationSlider
        aspectSlider={true}
        quality={1}
        showReset={true}
        modalTitle="编辑图片"
        cropShape="rect"
        showGrid
        // cropperProps={}
        // aspect={10}
        // minZoom={1}
        // maxZoom={100}
      >
        {props.target === 'cover' ? (
          <Upload
            {...draggerProps}
            name="file"
            listType="picture-card"
            fileList={props.fileList}
            onChange={onChange}
            onPreview={onPreview}
            onRemove={onRemove}
            headers={{'Token':'Bearer ' + window.sessionStorage.getItem('userToken')}}
          >
            {props.fileList.length < 1 && '+ 上传封面'}
          </Upload>
        ) : (
          <Dragger
            {...draggerProps}
            name="file"
            listType="picture-card"
            fileList={props.fileList}
            onChange={onChange}
            onPreview={onPreview}
            onRemove={onRemove}
          >
            {/* {props.fileList.length < 5 && '+ Upload'} */}
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">点击或拖动文件上传</p>
            <p className="ant-upload-hint">严禁上传包含色情、暴力、反动等相关违法信息的文件。</p>
          </Dragger>
        )}
      </ImgCrop>
      <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
        <img alt="example" style={{ width: '100%' }} src={previewImage} />
      </Modal>
    </>
  );
};

export default App;
